#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2024/12/6 21:16
# @Author  : 唐松
# @File    : requests_util.py
# @Software: PyCharm

import json
import re
import requests
from requests import utils
from configs.config import write_extract_yaml
from util_tools.logger_util import logs


class RequestsUtil:

    def __init__(self):
        pass

    @classmethod
    def _test_encode(cls, res_text):
        """
        处理接口返回值中, 出现unicode编码 \\u767d
        :param res_text: 接口返回值
        :return: 处理后的返回值
        """
        match = re.search(r"\\u[0-9a-fA-F]{4}", res_text)
        if match:
            result = res_text.encode().decode('unicode_escape')
        else:
            result = res_text
        return result

    def send_request(self, **kwargs):
        """
        发送请求
        :param kwargs: 请求参数
        :return:
            response: 请求响应
        """
        with requests.Session() as session:
            response = None
        try:
            # 发送请求
            response = session.request(**kwargs)
            # 获取响应中的cookie
            set_cookie = requests.utils.dict_from_cookiejar(response.cookies)
            # 如果存在cookie, 将cookie写入yaml文件中
            if set_cookie:
                # print(f'获取到cookie: {set_cookie}')
                write_extract_yaml({'Cookie': set_cookie})
            res = self._test_encode(response.text)
            # print(res)
        except requests.exceptions.ConnectionError:
            logs.error('接口请求异常,可能是request的链接过多或者速度过快导致程序报错! ')
        except requests.exceptions.RequestException as e:
            logs.error('请求异常,请检查系统数据是否正常!')
        return response

    def execute_request(self, name, method, url, headers=None, cookies=None, files=None, **kwargs):
        """
        执行请求
        :param name: 接口名称
        :param method: 请求方式
        :param url: 请求地址
        :param headers: 请求头
        :param cookies: cookies
        :param files:   文件上传
        :param kwargs:  请求参数 如data、json、params等
        :return:
        """
        logs.info('---------------------------------接口测试开始---------------------------------')
        logs.info(f'接口名称: {name}')
        logs.info(f'请求地址: {url}')
        logs.info(f'请求方式: {method}')
        logs.info(f'headers值: {headers}')
        logs.info(f'cookies值: {cookies}')
        yaml_kwargs_type = kwargs.keys()
        if kwargs and ('data' in yaml_kwargs_type or 'json' in yaml_kwargs_type or 'params' in yaml_kwargs_type):
            params_type = list(kwargs.keys())[0]
            logs.info(f'参数类型: {params_type}')
            params = json.dumps(list(kwargs.values())[0], ensure_ascii=False)
            logs.info(f'请求参数: {params}')
        response = self.send_request(
            method=method,
            url=url,
            headers=headers,
            cookies=cookies,
            files=files,
            timeout=10,
            verify=True,
            **kwargs)

        return response


if __name__ == '__main__':
    url = "http://127.0.0.1:8787/dar/user/addUser"
    method = 'post'
    header = {
        "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8 "
    }
    data = {
          "username": "testadduser",
          "password": "tset6789890",
          "role_id": '123456789',
          "dates": '2024-12-31',
          "phone": '13800000000',
          "token": '82906F55eF8Df5eC707E15599d158'
    }
    send = RequestsUtil()
    res = send.execute_request(name=None, url=url, headers=header, method=method, data=data)
    print(res.text)
    # base_url = read_config_file('base', 'base_url')
    # caseinfo = read_testcase_file('testcase/userManager/addUser.yaml')[0]
    # print(caseinfo)
    # url = base_url + caseinfo['request']['path']
    # print(url)
    # method = caseinfo['request']['method']
    # data = caseinfo['request']['data']
    # headers = caseinfo['request']['headers']
    # print(headers)
    # send = RequestsUtil()
    # res = send.execute_request(name=None, url=url, headers=headers, method=method, data=data)
    # res_json = res.json()
    # print(res_json)
    # token = res_json['token']
    # user_id = res_json['userId']
    # write_extract_yaml({'token': token, 'user_id': user_id})
